<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import type { TableInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import ajax from "../main.ts";

interface McpItem {
  id: string
  name: string
  category: string
  classification: string
  description: string
  author: string
  githubUrl: string
  status: 'pending' | 'processing' | 'success' | 'failed'
  office: number
}

const statusOptions = [
  { value: '待处理', label: '待处理' },
  { value: '处理中', label: '处理中' },
  { value: '成功', label: '成功' },
  { value: '失败', label: '失败' },
  { value: '全部', label: '全部' }
]

const searchForm = reactive({
  status: '待处理',
  keyword: ''
})

const tableData = ref<McpItem[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const dialogVisible = ref(false)
const auditDialogVisible = ref(false)
const editForm = reactive({
  id: '',
  name: '',
  status: '',
  office: 0
})

const auditForm = reactive({
  id: '',
  isOfficial: 0,
  githubUrl: ''
})

const officialOptions = [
  { value: 1, label: '是' },
  { value: 0, label: '否' }
]

const editStatusOptions = [
  { value: '处理中', label: '处理中' },
  { value: '待处理', label: '待处理' },
  { value: '成功', label: '成功' },
  { value: '失败', label: '失败' }
]

const getStatusType = (status: string) => {
  switch (status) {
    case '待处理':
      return 'warning'
    case '处理中':
      return 'info'
    case '成功':
      return 'success'
    case '失败':
      return 'danger'
    default:
      return ''
  }
}

const getStatusLabel = (status: string) => {
  switch (status) {
    case '待处理':
      return '待处理'
    case '处理中':
      return '处理中'
    case '成功':
      return '成功'
    case '失败':
      return '失败'
    default:
      return ''
  }
}

const fetchTableData = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      status: searchForm.status,
      keyword: searchForm.keyword
    }
    const { data } = await ajax.post('getMcpManage/', params)
    if (data.code === 200) {
      tableData.value = data.list
      total.value = data.total
    } else {
      ElMessage.error(data.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败：', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchTableData()
}

const handleReset = () => {
  searchForm.status = '待处理'
  searchForm.keyword = ''
  currentPage.value = 1
  fetchTableData()
}

const handleAudit = (row: McpItem) => {
  auditForm.id = row.id
  auditForm.isOfficial = 0
  auditForm.githubUrl = row.githubUrl
  auditDialogVisible.value = true
}

const handleAuditConfirm = async () => {
  try {
    const { data } = await ajax.post('confirmMcp/', {
      id: auditForm.id,
      isOfficial: auditForm.isOfficial,
      githubUrl: auditForm.githubUrl
    })
    if (data.code === 200) {
      ElMessage.success('审核成功')
      auditDialogVisible.value = false
      await fetchTableData()
    } else {
      ElMessage.error(data.msg || '审核失败')
    }
  } catch (error) {
    console.error('审核失败：', error)
    ElMessage.error('审核失败')
  }
}

const handleDelete = async (row: McpItem) => {
  try {
    const confirmResult = await ElMessageBox.confirm(
      '确定要删除该MCP吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    if (confirmResult === 'confirm') {
      const { data } = await ajax.post('delMcp/', { id: row.id })
      if (data.code === 200) {
        ElMessage.success('删除成功')
        await fetchTableData()
      } else {
        ElMessage.error(data.msg || '删除失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败：', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleEdit = (row: McpItem) => {
  editForm.id = row.id
  editForm.name = row.name
  editForm.status = row.status
  editForm.office = row.office
  dialogVisible.value = true
}

const handleEditConfirm = async () => {
  try {
    const { data } = await ajax.post('updateMcp/', {
      id: editForm.id,
      status: editForm.status,
      office: editForm.office
    })
    if (data.code === 200) {
      ElMessage.success('修改成功')
      dialogVisible.value = false
      await fetchTableData()
    } else {
      ElMessage.error(data.msg || '修改失败')
    }
  } catch (error) {
    console.error('修改失败：', error)
    ElMessage.error('修改失败')
  }
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchTableData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchTableData()
}

onMounted(() => {
  fetchTableData()
})
</script>

<template>
  <div class="mcp-manage">
    <el-card class="search-card" shadow="never">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            class="status-select"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入关键词搜索"
            class="search-input"
            :prefix-icon="Search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        empty-text="没有数据"
      >
        <el-table-column prop="id" label="MCP ID" width="120" />
        <el-table-column prop="name" label="名称" width="120" />
        <el-table-column prop="category" label="类别" width="120" />
        <el-table-column prop="classification" label="分类" width="120" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="githubUrl" label="Github地址" width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link type="primary" :href="row.githubUrl" target="_blank">
              {{ row.githubUrl }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              effect="light"
              class="status-tag"
            >
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <div class="operation-links">
              <template v-if="row.status === '待处理'">
                <el-link type="primary" @click="handleEdit(row)">修改</el-link>
                <el-divider direction="vertical" />
                <el-link type="primary" @click="handleAudit(row)">审核</el-link>
                <el-divider direction="vertical" />
                <el-link type="danger" @click="handleDelete(row)">删除</el-link>
              </template>
              
              <template v-if="row.status === '处理中'">
                <el-link type="primary" @click="handleAudit(row)">重试</el-link>
                <el-divider direction="vertical" />
                <el-link type="danger" @click="handleDelete(row)">删除</el-link>
              </template>
              
              <template v-if="row.status === '成功'">
                <el-link type="primary" @click="handleAudit(row)">重试</el-link>
                <el-divider direction="vertical" />
                <el-link type="primary" @click="handleEdit(row)">修改</el-link>
                <el-divider direction="vertical" />
                <el-link type="danger" @click="handleDelete(row)">删除</el-link>
              </template>
              
              <template v-if="row.status === '失败'">
                <el-link type="primary" @click="handleAudit(row)">重试</el-link>
                <el-divider direction="vertical" />
                <el-link type="danger" @click="handleDelete(row)">删除</el-link>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 修改弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="修改MCP状态"
      width="500px"
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="ID">
          <el-input v-model="editForm.id" disabled />
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="editForm.name" disabled />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option
              v-for="item in editStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否官方">
          <el-select v-model="editForm.office" placeholder="请选择是否官方" style="width: 100%">
            <el-option
              v-for="item in officialOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 审核弹窗 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="MCP审核"
      width="500px"
    >
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="ID">
          <el-input v-model="auditForm.id" disabled />
        </el-form-item>
        <el-form-item label="Github地址">
          <el-input v-model="auditForm.githubUrl" placeholder="请输入Github地址" />
        </el-form-item>
        <el-form-item label="是否官方">
          <el-select v-model="auditForm.isOfficial" placeholder="请选择是否官方" style="width: 100%">
            <el-option
              v-for="item in officialOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAuditConfirm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.mcp-manage {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.status-select {
  width: 160px;
}

.search-input {
  width: 240px;
}

.table-card {
  border-radius: 8px;
}

.status-tag {
  min-width: 70px;
  text-align: center;
}

.operation-links {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
}

:deep(.el-link) {
  font-size: 13px;
}

:deep(.el-divider) {
  margin: 0 4px;
}
</style>